package handler

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"live-broadcast_07_22/api/request"
	"live-broadcast_07_22/global"
	"live-broadcast_07_22/internal/model"
	"live-broadcast_07_22/pkg"
	"net/http"
	"path/filepath"
	"strings"
	"time"
)

func RegisterUser(c *gin.Context) {

	var req request.RegisterUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	user.Mobile = req.Mobile
	user.Password = pkg.Md5(req.Password)

	user.GetOneUser(req.Mobile)

	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "禁止重复注册",
			"data": nil,
		})
		return
	}
	user.AddUser()

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"data": nil,
	})

	fmt.Println(user)

}

func LoginUser(c *gin.Context) {

}

func Upload(c *gin.Context) {

	var user model.User

	file, err := c.FormFile("image")
	if err != nil {
		return
	}

	get := global.RDB.Get(context.Background(), "upload")
	if get.Val() != "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "10 秒内最多允许上传 1 次",
			"data": nil,
		})
		return
	}

	etc := strings.ToLower(filepath.Ext(file.Filename))
	if !strings.Contains(".jpg.png.mp4", etc) {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "文件格式仅允许.jpg/.png/.mp4",
			"data": nil,
		})
		return
	}

	if etc == ".mp4" {
		if file.Size > 50*1024*1024 {
			c.JSON(http.StatusOK, gin.H{
				"code": 100000,
				"msg":  "视频最大 50MB",
				"data": nil,
			})
			return
		}
	} else {
		if file.Size > 2*1024*1024 {
			c.JSON(http.StatusOK, gin.H{
				"code": 100000,
				"msg":  "图片最大 2MB",
				"data": nil,
			})
			return
		}
	}

	pkg.Upload()

	global.RDB.Set(context.Background(), "upload", 1, 10*time.Second)
	global.RDB.Incr(context.Background(), fmt.Sprintf("upload:%d", user.Id))

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "文件上传成功",
		"data": nil,
	})

}

func DeleteUpload(c *gin.Context) {

}

func GetUploadNum(c *gin.Context) {

}

func ListUpload(c *gin.Context) {
	
}

func ShowUpload(c *gin.Context) {
	
}